package com.pingan.glue.gluegame.controller;

import com.pingan.glue.gluegame.common.ErrorMessage;
import com.pingan.glue.gluegame.common.utils.FileUtils;
import com.pingan.glue.gluegame.controller.form.FriendLoginForm;
import com.pingan.glue.gluegame.controller.form.LoginResponse;
import com.pingan.glue.gluegame.entity.FaceFieldEntity;
import com.pingan.glue.gluegame.entity.FriendUserEntity;
import com.pingan.glue.gluegame.entity.FriendUserTokenEntity;
import com.pingan.glue.gluegame.response.ResponseData;
import com.pingan.glue.gluegame.response.ResponseResult;
import com.pingan.glue.gluegame.service.FaceService;
import com.pingan.glue.gluegame.service.FriendUserService;
import com.pingan.glue.gluegame.service.FriendUserTokenService;
import com.pingan.glue.gluegame.service.SysCaptchaService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

@Controller
@RequestMapping("login")
public class FriendUserLoginController {

    private final static Logger LOGGER = LoggerFactory.getLogger(FriendUserLoginController.class);

    @Resource
    private SysCaptchaService sysCaptchaService;
    @Resource
    private FriendUserService friendUserService;
    @Resource
    private FriendUserTokenService friendUserTokenService;
    @Resource
    private FaceService faceService;


    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid)throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }


    @PostMapping
    private @ResponseBody
    ResponseData<LoginResponse> login(@RequestBody FriendLoginForm form){
        LOGGER.info("FriendUserLoginController_login_params={}",form);
        if (StringUtils.isBlank(form.getCode())||StringUtils.isBlank(form.getMobile())) {
            return ResponseData.error(ErrorMessage.MOBILE_CODE_NOT_NULL);
        }

      /*  boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
        if(!captcha){
            return ResponseData.error(ErrorMessage.CAPTCHA);
        }*/

        //用户信息
        FriendUserEntity user = friendUserService.queryByMobile(form.getMobile());
        if(user == null) {
            user = new FriendUserEntity();
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());

            user.setMobile(form.getMobile());
            user.setStatus(1);
            Integer i = friendUserService.createUser(user);
            user = friendUserService.queryByMobile(form.getMobile());
        }

        FaceFieldEntity face= faceService.queryFaceFromDb(user.getUserId());
        //生成token，并保存到数据库
        String token = friendUserTokenService.createToken(user.getUserId());
        LoginResponse lr = new LoginResponse();
        lr.setToken(token);
        lr.setHaveImages(face != null);
        return ResponseData.success(lr);
    }

    @PostMapping("face")
    public @ResponseBody
    ResponseData<LoginResponse> face(@RequestParam("fileName") MultipartFile file){
        LOGGER.info("FriendUserLoginController_face: start(人脸登陆)");
        try{
            String image = Base64.getEncoder().encodeToString(file.getBytes());
            String userId = faceService.loginFace(image);
            FriendUserEntity user = friendUserService.queryUser(Long.parseLong(userId));
            String token = friendUserTokenService.createToken(user.getUserId());
            FaceFieldEntity face= faceService.queryFaceFromDb(user.getUserId());
            LoginResponse lr = new LoginResponse();
            lr.setToken(token);
            lr.setHaveImages(face != null);
            return ResponseData.success(lr);
        }catch (Exception e){
            return ResponseData.error(ErrorMessage.FACE_LOGIN_ERROR);
        }
    }

    @PostMapping("otp")
    public @ResponseBody
    ResponseData<String> otp(@RequestParam("mobile") String mobile){
        LOGGER.info("FriendUserLoginController_otp_param:{}",mobile);
        try{

            return ResponseData.success(null);
        }catch (Exception e){
            return ResponseData.error(ErrorMessage.FACE_LOGIN_ERROR);
        }
    }


    @PostMapping("loginValidate")
    public @ResponseBody
    ResponseData<String> loginValidate(@RequestParam("token") String token){
        LOGGER.info("FriendUserLoginController_loginIsValidate_param:{}",token);
        try{
            //根据accessToken，查询用户信息
            FriendUserTokenEntity tokenEntity = friendUserTokenService.queryByToken(token);
            //token失效
            if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
                return ResponseData.error(ErrorMessage.TOKEN_IS_ERROR);
            }
            return ResponseData.success(null);
        }catch (Exception e){
            return ResponseData.error(ErrorMessage.TOKEN_IS_ERROR);
        }
    }


}
